<template>
  <div>
    <PageWrapper :class="prefixCls" title="分类列表">
      <template #headerContent>
        <a-button type="primary" @click="showModal(0)">新增分类</a-button>
      </template>
      <div :class="`${prefixCls}__content`">
        <a-collapse
          v-model:activeKey="activeKeyStore.activeKey"
          :bordered="false"
          class="mt-3 mb-3"
          style="background: rgb(255 255 255)"
          @change="handleChange"
          v-if="list.length"
        >
          <template v-for="item in list" :key="item.id">
            <a-collapse-panel
              style="margin-bottom: 10px; border: 0; border-radius: 4px; background: #f5f5f5"
            >
              <template #header>
                <div class="fl-list-head">
                  <div class="fl-list-head-in">{{ item.name }}</div>
                  <div class="fl-list-head-but">
                    <a class="add list-but" title="新增二级分类" @click.stop="showModal(item.id)">
                      新增
                    </a>
                    <a class="add list-but" title="上传文件" @click.stop="toPath(item.id, '')">
                      上传
                    </a>
                    <a
                      class="add list-but"
                      title="更改分类名称"
                      @click.stop="updateHandle(item.id, item.name, 0)"
                    >
                      编辑
                    </a>
                    <a
                      class="delete list-but"
                      title="删除一级分类"
                      @click.stop="showDeleteConfirm(item.id)"
                    >
                      删除
                    </a>
                  </div>
                </div>
              </template>
              <div>
                <template v-for="er in item.levelTowCategoryList" :key="er.id">
                  <div class="fl-list-er">
                    <div class="fl-list-er-in" @click.stop="toPath(item.id, er.id)">{{
                      er.name
                    }}</div>
                    <div class="fl-list-er-but">
                      <a class="add list-but" title="上传文件" @click.stop="toPath(item.id, er.id)">
                        上传
                      </a>
                      <a
                        class="add list-but"
                        title="更改分类名称"
                        @click.stop="updateHandle(er.id, er.name, item.id)"
                      >
                        编辑
                      </a>
                      <a
                        class="delete list-but"
                        title="删除二级分类"
                        @click.stop="showDeleteConfirm(er.id)"
                      >
                        删除
                      </a>
                    </div>
                  </div>
                </template>
              </div>
            </a-collapse-panel>
          </template>
        </a-collapse>
        <List v-else />
      </div>
    </PageWrapper>
    <!-- 添加分类弹窗 -->
    <a-modal v-model:open="open" :title="modalTitle" @ok="handleOk" :closable="false">
      <template #footer>
        <div class="add-footer">
          <a-button key="back" @click="handleCancel">取消</a-button>
          <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确认</a-button>
        </div>
      </template>
      <div class="add-input">
        <a-input
          v-model:value="nameValue"
          placeholder="请输入分类名称"
          :maxlength="100"
          :status="inputStatus"
          :allowClear="true"
          @input="inputStatus = ''"
        />
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, createVNode, onMounted } from 'vue';
  import { message, Modal, List } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { useGo } from '@/hooks/web/usePage';
  import { addCategory, deleteCategory, getAllCategory, updateCategory } from '@/api/home/images';
  import { useActiveKeyStore } from '@/store/home/classification';

  const go = useGo();
  const prefixCls = 'list-basic';

  // 展开的分类id
  const activeKey = ref([]);
  // 分类列表的缓存数据
  const activeKeyStore = useActiveKeyStore();
  // 展开或者收起分类事件
  const handleChange = (key: never[]) => {
    activeKey.value = key;
    activeKeyStore.setActiveKey(key);
  };
  // 在组件挂载时缓存参数
  onMounted(() => {
    getList();
  });

  // 分类名称
  const nameValue = ref('');

  interface itemData {
    id: number;
    name: string;
    levelTowCategoryList: itemData[];
  }
  const list = ref<itemData[]>([]);
  // 跳转添加图片页面
  const toPath = (categoryOneId: any, categoryTwoId: any) => {
    const path = categoryTwoId
      ? `/home/images-list?categoryOneId=${categoryOneId}&categoryTwoId=${categoryTwoId}`
      : `/home/images-list?categoryOneId=${categoryOneId}`;
    go(path);
  };

  const loading = ref(false);
  const open = ref(false);
  const modalTitle = ref('添加分类');
  const modalType = ref('add');
  const parentId = ref<number | string>(0);
  // 如果携带了id 就是添加二级分类
  const showModal = (id?: number | string) => {
    parentId.value = id || 0;
    modalType.value = 'add';
    modalTitle.value = '添加分类';
    open.value = true;
  };

  const inputStatus = ref('');
  // 分类确定事件
  const handleOk = async () => {
    try {
      if (!nameValue.value) {
        return (inputStatus.value = 'error');
      }
      loading.value = true;
      if (modalType.value === 'add') {
        await addCategoryFun();
      } else if (modalType.value === 'edit') {
        await updateCategoryFun();
      }
    } catch (error) {
      loading.value = true;
    }
  };
  // 新增分类
  const addCategoryFun = async () => {
    try {
      await addCategory({
        name: nameValue.value,
        parentId: parentId.value,
      });
      loading.value = false;
      message.success('新增成功');
      handleCancel();
      await getList();
    } catch (error) {
      loading.value = false;
    }
  };
  // 新增分类取消事件
  const handleCancel = () => {
    nameValue.value = '';
    open.value = false;
    parentId.value = 0;
  };
  // 编辑分类
  const editParams = ref({
    id: null,
    name: '',
    parentId: 0,
  });
  const updateHandle = (id: any, name: string, pid: any) => {
    modalType.value = 'edit';
    modalTitle.value = '编辑分类';
    nameValue.value = name;
    editParams.value = { id, name, parentId: pid };
    open.value = true;
  };
  const updateCategoryFun = async () => {
    try {
      await updateCategory({
        ...editParams.value,
        name: nameValue.value,
      });
      loading.value = false;
      message.success('编辑成功');
      handleCancel();
      await getList();
    } catch (error) {
      loading.value = false;
    }
  };

  // 分类删除
  const showDeleteConfirm = async (id: any) => {
    if (!id) {
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '是否确定删除该分类?',
      icon: createVNode(ExclamationCircleOutlined),
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      async onOk() {
        try {
          await deleteCategory(id);
          message.success('删除成功');
          getList();
        } catch (error) {
          console.log(error);
        }
      },
    });
  };
  // 获取分类列表
  const getList = async () => {
    try {
      const data = await getAllCategory();
      list.value = data || [];
    } catch (error) {
      console.log(error);
    }
  };
</script>
<style lang="less" scoped>
  .ant-input-affix-wrapper {
    padding: 8px 11px;
  }

  .add-footer {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .add-input {
    padding: 10px 0;
    font-size: 16px;
  }

  .list-but {
    padding: 0 5px;
    cursor: pointer;
  }

  .list-but:hover {
    color: #0075fc;
  }

  .fl-list {
    display: block;
    border-bottom: 1px solid #e8e8e8;

    &-er {
      display: flex;
      position: relative;
      align-items: center;
      justify-content: space-between;
      padding: 5px 0;
      font-size: 14px;

      &-in {
        flex: 1;
        padding: 0 20px;
        cursor: pointer;
      }

      &-but {
        display: flex;
      }
    }

    &-er::before {
      content: '';
      display: block;
      position: absolute;
      top: 11px;
      left: 5px;
      width: 4px;
      height: 4px;
      border-radius: 50%;
      background: #999;
    }

    &-er:hover::before {
      background: #0075fc;
    }

    &-er:hover .fl-list-er-in {
      color: #0075fc;
    }

    &-head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 16px;

      &-in {
        flex: 1;
        padding-right: 20px;
        line-height: 1.5;
        cursor: pointer;
      }

      &-but {
        display: flex;
        align-items: center;
        font-size: 14px;
      }
    }

    &-head:hover .fl-list-head-in {
      color: #0075fc;
    }
  }

  .fl-list:last-child {
    border-bottom: none;
  }

  :deep(.ant-page-header) {
    padding: 15px 24px;
  }

  .list-basic {
    &__content {
      padding: 10px 20px;
      background-color: @component-background;

      .list {
        position: relative;
      }
    }
  }
</style>
